<!-- src/views/company/Profile.vue -->
<template>
  <div class="company-profile">
    <div class="profile-header">
      <h2>企业信息</h2>
      <el-button
        v-if="!isEditing"
        type="primary"
        @click="startEdit"
      >
        编辑信息
      </el-button>
      <div v-if="profile.status === 2" class="reject-warning">
        <el-alert
          :title="`信息审核被拒绝: ${profile.rejectReason || '未提供拒绝原因'}`"
          type="error"
          show-icon
          :closable="false"
        />
      </div>
      <div v-if="profile.status === 0" class="pending-warning">
        <el-alert
          title="信息正在审核中，请耐心等待"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>
    </div>

    <el-card class="profile-card">
      <div v-if="!isEditing">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="企业名称">{{ profile.name }}</el-descriptions-item>
          <el-descriptions-item label="统一社会信用代码">{{ profile.unifiedCode }}</el-descriptions-item>
          <el-descriptions-item label="法人代表">{{ profile.legalPerson }}</el-descriptions-item>
          <el-descriptions-item label="注册资本">{{ formatCurrency(profile.registeredCapital) }} 元</el-descriptions-item>
          <el-descriptions-item label="成立日期">{{ profile.establishmentDate }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ profile.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ profile.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="联系邮箱">{{ profile.contactEmail }}</el-descriptions-item>
          <el-descriptions-item label="企业网址">{{ profile.website || '无' }}</el-descriptions-item>
          <el-descriptions-item label="企业Logo">{{ profile.logo || '无' }}</el-descriptions-item>
          <el-descriptions-item label="企业地址" :span="2">{{ profile.address }}</el-descriptions-item>
          <el-descriptions-item label="经营范围" :span="2">{{ profile.businessScope }}</el-descriptions-item>
          <el-descriptions-item label="企业简介" :span="2">{{ profile.introduction }}</el-descriptions-item>
          <el-descriptions-item label="审核状态" :span="2">
            <el-tag :type="getStatusType(profile.status)">
              {{ getStatusLabel(profile.status) }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <div class="action-buttons" v-if="profile.status === 2">
          <el-button
            type="success"
            @click="resubmitForReview"
            :loading="submitLoading"
            style="margin-top: 20px"
          >
            重新提交审核
          </el-button>
        </div>
      </div>

      <div v-else>
        <el-form
          :model="profileForm"
          :rules="profileRules"
          ref="profileFormRef"
          label-width="150px"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="企业名称" prop="name">
                <el-input v-model="profileForm.name" placeholder="请输入企业名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="统一社会信用代码" prop="unifiedCode">
                <el-input v-model="profileForm.unifiedCode" placeholder="请输入统一社会信用代码" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="法人代表" prop="legalPerson">
                <el-input v-model="profileForm.legalPerson" placeholder="请输入法人代表" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="注册资本(元)" prop="registeredCapital">
                <el-input-number
                  v-model="profileForm.registeredCapital"
                  :min="0"
                  controls-position="right"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="成立日期" prop="establishmentDate">
                <el-date-picker
                  v-model="profileForm.establishmentDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择成立日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人" prop="contactPerson">
                <el-input v-model="profileForm.contactPerson" placeholder="请输入联系人" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系电话" prop="contactPhone">
                <el-input v-model="profileForm.contactPhone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系邮箱" prop="contactEmail">
                <el-input v-model="profileForm.contactEmail" placeholder="请输入联系邮箱" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="企业网址" prop="website">
                <el-input v-model="profileForm.website" placeholder="请输入企业网址" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="企业Logo" prop="logo">
                <el-input v-model="profileForm.logo" placeholder="请输入Logo URL" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="企业地址" prop="address">
            <el-input v-model="profileForm.address" placeholder="请输入企业地址" />
          </el-form-item>

          <el-form-item label="经营范围" prop="businessScope">
            <el-input
              v-model="profileForm.businessScope"
              type="textarea"
              :rows="3"
              placeholder="请输入经营范围"
            />
          </el-form-item>

          <el-form-item label="企业简介" prop="introduction">
            <el-input
              v-model="profileForm.introduction"
              type="textarea"
              :rows="4"
              placeholder="请输入企业简介"
            />
          </el-form-item>

          <el-form-item>
            <el-button @click="cancelEdit">取消</el-button>
            <el-button
              type="primary"
              @click="submitProfile"
              :loading="submitLoading"
            >
              保存
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useCompanyStore } from '../../store/company'
import { ElMessage, ElMessageBox } from 'element-plus'

const companyStore = useCompanyStore()

const profile = ref({})
const isEditing = ref(false)
const submitLoading = ref(false)
const profileFormRef = ref()

const profileForm = reactive({
  name: '',
  unifiedCode: '',
  legalPerson: '',
  registeredCapital: 0,
  establishmentDate: '',
  businessScope: '',
  address: '',
  contactPerson: '',
  contactPhone: '',
  contactEmail: '',
  website: '',
  introduction: '',
  logo: ''
})

const profileRules = {
  name: [{ required: true, message: '请输入企业名称', trigger: 'blur' }],
  unifiedCode: [{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }],
  legalPerson: [{ required: true, message: '请输入法人代表', trigger: 'blur' }],
  contactPerson: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
  ],
  contactEmail: [
    { required: true, message: '请输入联系邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 获取企业信息
const fetchProfile = async () => {
  try {
    const data = await companyStore.fetchProfile()
    profile.value = data

    // 初始化表单数据
    Object.keys(profileForm).forEach(key => {
      profileForm[key] = data[key] || ''
    })
  } catch (error) {
    ElMessage.error('获取企业信息失败: ' + (error.message || '未知错误'))
  }
}

// 开始编辑
const startEdit = () => {
  isEditing.value = true
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  // 重置表单数据
  Object.keys(profileForm).forEach(key => {
    profileForm[key] = profile.value[key] || ''
  })

  if (profileFormRef.value) {
    profileFormRef.value.clearValidate()
  }
}

// 提交企业信息
const submitProfile = async () => {
  if (!profileFormRef.value) return

  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const updateData = { ...profileForm }
        await companyStore.updateProfile(updateData)
        ElMessage.success('企业信息更新成功')
        isEditing.value = false
        fetchProfile()
      } catch (error) {
        ElMessage.error('更新失败: ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 重新提交审核
const resubmitForReview = () => {
  ElMessageBox.confirm(
    '确定要重新提交企业信息进行审核吗？',
    '重新提交审核',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    submitLoading.value = true
    try {
      await companyStore.submitForReview()
      ElMessage.success('重新提交审核成功，请等待管理员审核')
      fetchProfile()
    } catch (error) {
      ElMessage.error(error.message || '提交审核失败')
    } finally {
      submitLoading.value = false
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 格式化金额
const formatCurrency = (amount) => {
  if (!amount) return '0.00'
  return parseFloat(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'   // 待审核
    case 1: return 'success' // 审核通过
    case 2: return 'danger'  // 审核拒绝
    default: return ''
  }
}

// 获取状态标签
const getStatusLabel = (status) => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '审核通过'
    case 2: return '审核拒绝'
    default: return '未知状态'
  }
}

onMounted(() => {
  fetchProfile()
})
</script>

<style scoped>
.company-profile {
  padding: 20px;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.reject-warning, .pending-warning {
  margin-top: 15px;
  width: 100%;
}

.action-buttons {
  display: flex;
  justify-content: center;
}
</style>
